﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using wenku8.Entity;
using wenku8.Parser;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// https://go.microsoft.com/fwlink/?LinkId=234238 上介绍了“空白页”项模板

namespace wenku8.Xamls
{
    /// <summary>
    /// 可用于自身或导航至 Frame 内部的空白页。
    /// </summary>
    public sealed partial class BookItemsPage : Page
    {
        private static int pageNum;
        private static string kind;
        private static string localTitle;
        private ObservableCollection<BookItem> BookItems { get; set; }
        public string RequestURI { get; private set; }

        public static readonly Dictionary<string, string> ButtonName2UriDictionary = new Dictionary<string, string>
        {
            ["hotNovelsButton"] = BaseURIs.hotNovelsURI,
            ["animatedNovelsButton"] = BaseURIs.animatedNovelsURI,
            ["updatedNovelsButton"] = BaseURIs.updatedNovelsURI,
            ["newNovelsButton"] = BaseURIs.newNovelsURI,
            ["completeNovelsButton"] = BaseURIs.completeNovelsURI,
            ["favouriteNovelsButton"] = BaseURIs.favouriteNovelsURI,
        };

        public static readonly Dictionary<string, string> ButtonName2TitleDictionary = new Dictionary<string, string>
        {
            ["hotNovelsButton"] = "热门轻小说",
            ["animatedNovelsButton"] = "动画化作品",
            ["updatedNovelsButton"] = "今日更新",
            ["newNovelsButton"] = "新书一览",
            ["completeNovelsButton"] = "完结全本",
            ["favouriteNovelsButton"] = "特别收藏",
        };

        public BookItemsPage()
        {
            this.InitializeComponent();
            BookItems = new ObservableCollection<BookItem>();
        }

        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New) {
                var button = e.Parameter as Button;
                RequestURI = ButtonName2UriDictionary[button.Name];
                localTitle = MainPage.TitleTextBlock.Text = ButtonName2TitleDictionary[button.Name];

                pageNum = 1;
                string htmlPage = null;
                if (button.Name == "favouriteNovelsButton") {
                    kind = "special";
                    htmlPage = await HTMLParser.GetHtmlString(RequestURI);
                }
                else {
                    kind = "normal";
                    htmlPage = await HTMLParser.GetHtmlString(RequestURI + "&page=" + pageNum++);
                }
                if (htmlPage == null) {
                    MainPage.PopMessageDialog("网络或服务器故障！");
                    return;
                }
                try {
                    BookItems.Clear();
                    BookItemParser.GetBookItems(htmlPage, BookItems, kind);
                    MainPage.DisableProgressRing();
                }
                catch (Exception) {
                    MainPage.PopMessageDialog("网络或服务器故障！");
                }
            }
            else if (e.NavigationMode == NavigationMode.Back) {
                MainPage.TitleTextBlock.Text = localTitle;
                MainPage.DisableProgressRing();
            }

            #region test code
            //for (var i = 0; i < 5; i++) {
            //    BookItems.Add(new BookItem()
            //    {
            //        Author = "东出佑一郎",
            //        Classification = "其他文库",
            //        Cover = await ImageHelper.GetImage(new Uri("http://img.wkcdn.com/image/1/1383/1383s.jpg"), "cover"),
            //        State = "已完成",
            //        Title = "fate apocrypha",
            //        LastUpdate = "2018-08-30"
            //    });
            //    BookItems.Add(new BookItem()
            //    {
            //        Author = "爱七ひろ",
            //        Classification = "富士见文库",
            //        Cover = await ImageHelper.GetImage(new Uri("http://img.wkcdn.com/image/1/1715/1715s.jpg"), "cover"),
            //        State = "连载中",
            //        Title = "爆肝工程师的异世界狂想曲(异世界狂想曲)",
            //        LastUpdate = "2018-09-11"
            //    });
            //}
            #endregion
        }

        bool flag = true;
        private async void BookItemsScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            if (kind == "special") {
                return;
            }
            if (BookItemsScrollViewer.VerticalOffset > BookItemsScrollViewer.ScrollableHeight - 10 && flag) {
                flag = false;
                MainPage.EnableProgressRing();
                var htmlPage = await HTMLParser.GetHtmlString(RequestURI + "&page=" + pageNum++);
                if (htmlPage == null) {
                    MainPage.PopMessageDialog("网络或服务器故障！");
                }
                else {
                    BookItemParser.GetBookItems(htmlPage, BookItems, "normal");
                }
                flag = true;
                MainPage.DisableProgressRing();
            }
        }

        // BookItem的点击响应
        private void BookItemsGridView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem is BookItem) {
                this.Frame.Navigate(typeof(BookDetalsPage), e.ClickedItem);
                MainPage.EnableProgressRing();
            }
        }
    }

    // 程序中用到的所有URI
    public class BaseURIs
    {
        public readonly static string hotNovelsURI = "https://www.wenku8.net/modules/article/toplist.php?sort=allvisit";
        public readonly static string animatedNovelsURI = "https://www.wenku8.net/modules/article/toplist.php?sort=anime";
        public readonly static string updatedNovelsURI = "https://www.wenku8.net/modules/article/toplist.php?sort=lastupdate";
        public readonly static string newNovelsURI = "https://www.wenku8.net/modules/article/toplist.php?sort=postdate";
        public readonly static string completeNovelsURI = "https://www.wenku8.net/modules/article/articlelist.php?fullflag=1";
        public readonly static string favouriteNovelsURI = "https://www.wenku8.net/modules/article/bookcase.php";

        public readonly static string collectNovelURI = "https://www.wenku8.net/modules/article/addbookcase.php?bid=";
        public readonly static string deleteNovelURI = "https://www.wenku8.net/modules/article/bookcase.php?delid=";
        public readonly static string voteNovelURI = "https://www.wenku8.net/modules/article/uservote.php?id=";
    }
}
